<?php

class pdo_util {

    private static $connection = null;

    public function __construct() {
        $this->dsn = "mysql:host=localhost;dbname=test";
        $this->user = "root";
        $this->pwd = "root";

        try {
            $pdo = new PDO($this->dsn, $this->user, $this->pwd);
            $pdo->exec("SET NAMES utf8");
        } catch (PDOException $e) {
            die("Connection fail:" . $e->getMessage());
        }
        self::$connection = $pdo;
    }


    // 查询
    public function select($table, $fields = '*', $where = null, $result_type = PDO::FETCH_ASSOC) {
        if ($fields == '*' and $where == null) {
            $sql = "select {$fields} from {$table} " . ($where == null ? null : "where " . $where);
            $stmt = self::$connection->prepare($sql);
            $stmt->execute();
            while ($row = $stmt->fetch($result_type)) {
                $rows[] = $row;
            }
            return $rows;
        }
        if ($where != null) {
            if (!is_array($where)) return false;
            $this->_array = $where;
            $where = $this->foreacharray();
            if ($where) {
                $sql = "select {$fields} from {$table} " . ($where == null ? null : "where " . $where);
                $stmt = self::$connection->prepare($sql);
                $stmt->execute();
                while ($row = $stmt->fetch($result_type)) {
                    $rows[] = $row;
                }
            }
            return $rows;
        }
    }

    // 添加
    public function add($table, array $array) {
        $keys = implode(',', array_keys($array));
        $values = '';
        foreach ($array as $val) {
            $values .= $val . ',';
        }
        $vals = str_replace(',', '\',\'', rtrim($values, ','));
        $sql = "insert into {$table} ($keys) values ('{$vals}')";
        return self::$connection->exec($sql);
    }

    // 修改
    public function update($table, $field, $where = null) {
        foreach ($field as $k => $v) {
            $fields .= $k .'=' . "'$v'" .',';
        }
        $fields = trim($fields, ',');
        $this->_array = $where;
        $where = $this->foreacharray();
        $sql = "update {$table} set {$fields} where " . $where;
        return self::$connection->exec($sql);
    }


    protected function foreacharray() {
        if (!is_array($this->_array)) return false;
        $str = '';
        foreach ($this->_array as $key => $val) {
            if ($key == $val) return false;
            $str .= $key . ' = ' . "'$val'" . ' and ';
        }
        return substr($str, 0, strrpos($str, 'and'));
    }


}